<?php

/**
 * 验证码类
 * @copyright eName.com.cn
 * @author wangjd 
 * @version 2010-11-18
 * 2010-11-29 updated by Johnson z
 */
class CaptchaLib
{

	public static function getCode($codeLength = 4)
	{
		return self::getLowerString($codeLength);
	}
	/**
	 * 随机字符串。小写
	 * @param int $length
	 * @return string
	 * note:time:2010-10-19 author:arden
	 */
	public static  function getLowerString($length)
	{
		$chars = "a,b,c,d,e,f,g,h,j,k,m,n,p,q,r,s,t,u,v,w,x,y,z";
		return self::generateRandomString($chars, $length);
	}

	public static function generateRandomString($chars, $length)
	{
		$chars_array = explode(',', $chars);
		$charsLen = count($chars_array) - 1;
		shuffle($chars_array);
		$output = '';
		for ($i = 0; $i < $length; $i ++)
		{
			$output .= $chars_array[mt_rand(0, $charsLen)];
		}
		return $output;
	}

	public static function showImage($code, $codeLength = 4, $width = 20, $height = 60)
	{
		$image = imagecreatetruecolor($height, $width);
		
		$width = imagesx($image);
		$height = imagesy($image);
		
		$bg_color = imagecolorallocate($image, 237,239,238);
		$text_color = imagecolorallocate($image, 60,146,173);
		$white = imagecolorallocate($image, 255, 255, 255);
		
		imagefilledrectangle($image, 0, 0, $width, $height, $bg_color);
		
		imagefilledrectangle($image, 0, 0, $width, 0, $white);
		imagefilledrectangle($image, $width - 1, 0, $width - 1, $height - 1, $white);
		imagefilledrectangle($image, 0, 0, 0, $height - 1, $white);
		imagefilledrectangle($image, 0, $height - 1, $width, $height - 1, $white);
		
		imagestring($image, 5, intval(($width - (strlen($code) * 9)) / 2), intval(($height - 15) / 2), $code, $text_color);
		
		header('Content-type: image/png');
		
		imagepng($image);
		
		imagedestroy($image);
	}

}
?>